package com.las.bot.cmd.jisu;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.las.bot.common.Constant;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseNonCommand;
import com.las.utils.HttpUtils;
import com.las.utils.StrUtils;
import com.las.utils.mirai.CmdUtil;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@BotCmd(funName = "疫情", isMatch = false)
public class YiQingCmd extends BaseNonCommand {

    private final Logger logger = Logger.getLogger(YiQingCmd.class);

    @Override
    public void execute(JSONObject obj, Long userId, Long id, Integer type, String cmd, ArrayList<String> args) throws Exception {
        if (args.size() == 1 && cmd.endsWith("疫情")) {
            cmd = cmd.replaceAll("疫情", "");
            cmd = cmd.replaceAll("#", "");
            String api = "https://c.m.163.com/ug/api/wuhan/app/data/list-total";
            String result = HttpUtils.doGet(api);
            if ("中国".equals(cmd)) {
                //timestamp
                JSONObject data = JSONObject.parseObject(result).getJSONObject("data");
                JSONObject json = data.getJSONObject("chinaTotal");
                json.put("lastUpdateTime", data.getString("lastUpdateTime"));
                sendMsg(userId, id, type, json, "中国");
            } else {
                JSONArray array = JSONObject.parseObject(result).getJSONObject("data").getJSONArray("areaTree");
                List<JSONObject> all = getAll(array, new ArrayList<>());
                for (JSONObject json : all) {
                    String name = json.getString("name");
                    if (name.startsWith(cmd.trim())) {
                        logger.info("疫情统计信息：" + json.toJSONString());
                        sendMsg(userId, id, type, json, name);
                        break;
                    }
                }
            }
        }
    }

    private void sendMsg(Long userId, Long id, Integer type, JSONObject json, String name) {
        StringBuilder sb = new StringBuilder();
        JSONObject total = json.getJSONObject("total");
        JSONObject today = json.getJSONObject("today");
        //JSONObject extData = json.getJSONObject("extData");
        String updateTime = json.getString("lastUpdateTime");
        sb.append(name).append("疫情：").append("\n");
        sb.append("累计确诊：").append(total.getIntValue("confirm")).append("\n");
        sb.append("累计死亡：").append(total.getIntValue("dead")).append("\n");
        int nowAll = total.getIntValue("confirm") - total.getIntValue("heal") - total.getIntValue("dead");
        sb.append("现有确诊：").append(nowAll).append("\n\n");
        sb.append("新增确诊：").append(Math.max(today.getIntValue("confirm"), 0)).append("\n");
        sb.append("更新时间：").append(updateTime);

        String[] split = sb.toString().split("\\n");
        String uuid = genImg(split);

        String fileName = uuid + ".png";
        logger.info("生成疫情图片：" + fileName);
        // 实现准备好空集合
        ArrayList<String> urls = new ArrayList<>();
        File file = new File(fileName);
        try {
            String objectName = uuid + Constant.BUCKET_PNG;
            // 下一步将目标图上传到阿里云
            String endpoint = Constant.HTTPS + Constant.OSS;
            String accessKeyId = Constant.BUCKET_ID;
            String accessKeySecret = Constant.BUCKET_KEY;
            String bucketName = Constant.BUCKET_NAME;
            // 上传到阿里云OSS
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, file);
            ossClient.shutdown();
            String imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;
            logger.info("上传到阿里云原图：" + imgUrl);
            urls.add(imgUrl);
            if (CollectionUtil.isNotEmpty(urls)) {
                CmdUtil.sendImgMessage(urls, userId, id, type);
            }
        } catch (Exception e) {
            logger.error("生成疫情图片失败：" + e.getMessage());
            CmdUtil.sendMessage("生成疫情图片失败...请稍后再试...", userId, id, type);
        } finally {
            // 上传成功后需要删除本地图
            if (file.exists()) {
                file.delete();
            }
        }

    }

    private static String genImg(String[] split) {
        int width = 400;
        int height = 200;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);//设置宽高，图片类型
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);//设置绘画的区域,默认背景是黑色，也叫做获取画笔，指定画笔可画的范围
        g.setColor(Color.white);//设置画笔颜色
        g.fillRect(0, 0, width, height);//画一个矩形块,颜色是白色，因为画笔颜色是白色
        g.setColor(Color.black);//设置画笔颜色
        g.setFont(new Font("宋体", Font.PLAIN, 22));//设计字体样式
        for (int i = 0; i < split.length; i++) {
            String str = split[i];
            g.drawString(str, 35,25 * (i + 1));
        }
        g.dispose();
        String fileId = StrUtils.uuid();
        try {
            ImageIO.write(image, "png", new File(fileId + ".png"));
        } catch (IOException ignored) {
        }
        return fileId;
    }

    private List<JSONObject> getAll(JSONArray array, List<JSONObject> list) {
        for (int i = 0; i < array.size(); i++) {
            JSONObject obj = array.getJSONObject(i);
            String name = obj.getString("name");
            if (name.startsWith("未明确") || name.startsWith("境外")) {
                continue;
            }
            list.add(obj);
            JSONArray children = obj.getJSONArray("children");
            if (CollectionUtil.isEmpty(children)) {
                list.add(obj);
            } else {
                getAll(children, list);
            }
        }
        return list;
    }
}
